<?php

class MemberAction extends CommonAction{

    public function __construct(){
        header('Location:/');
        exit;
    }

    /**
     * 登录页面
     */
    public function login(){
        if ($this->checkLogin(true)) {
            header('Location:/');
        }
        $re = $this->_get('re', 'trim', '');
        if ($re) {
            session('loginto', base64_decode($re));
        } else {
            if (!session('loginto')) {
                session('loginto', '/member/account.html');
            }
        }
        $this->display('login');
    }

    /**
     * 登录提交AJAX
     */
    public function dologin(){
        $post = $this->boxpost();
        $logerr = S('loginerr' . $post['username']) ? S('loginerr' . $post['username']) : 0;
        if ($logerr >= 5) {
            unset($_SESSION['verify']);
            $this->ajaxError('您的错误次数过多，请一小时后再试');
        }
        $post['verifycode'] = trim($post['verifycode']);
        if(empty($post['verifycode'])){
            unset($_SESSION['verify']);
            $this->ajaxError('请输入图片验证码');
        }
        if (!$this->verifycheck($post['verifycode'])) {
            unset($_SESSION['verify']);
            $this->ajaxError('图片验证码输入错误');
        }
        //查询用户基础信息
        $member = M("admin_user")->where(array('user_name' => $post['username'], 'is_deleted' => 0))->find();
        if (!$member) {
            $member = M("admin_user")->where(array('user_mobile' =>$post['username'], 'is_deleted' => 0))->select();
            if (!$member) {
                unset($_SESSION['verify']);
                $this->ajaxError("用户不存在");
            }
            if (count($member) > 1) {
                unset($_SESSION['verify']);
                $this->ajaxError('您的帐号只能通过用户名登录');
            }
            $member = $member[0];
        }
        //获取加密密码
        $submitpasswd = $this->gen_password($post['password']);
        if ( $submitpasswd != $member['user_pwd'] ) {
            S('loginerr' . $post['username'], $logerr + 1, 3600);
            unset($_SESSION['verify']);
            $this->ajaxError("密码错误");
        }
        if( $member['disabled_status'] == 1){
            $this->ajaxError("账户已被禁用，暂时无法登录");
        }
        if( $member['status'] == 0){
            $this->ajaxError("账户未启用，暂时无法登录");
        }
        //如果是代理，则查询代理信息
        if( $member['role_id'] == 3 ){
            $member_agent_info = M("admin_agent_info")->where(array('admin_id' => $member['id']))->find();
            if( $member_agent_info ){
                $member['agent_info'] = $member_agent_info;
            }
        }

        $session_id = session_id();
        S('pc_session_login_sessionId'.$member['id'],$session_id,86400);
        session('member', $member);
        session('loginto', '');
        $this->ajaxSuccess("登录成功");
    }

    /**
     * 我的账户
     */
    public function account(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        $member = session('member');
        //查询代理信息设置
        if($member['role_id'] == 3){
            $agent_info = M("admin_agent_info")->where(array('admin_id' => $member['id']))->find();
            //查询代理的商标总数
            $count = M("trademarks")->where(array("agent_id"=>$agent_info['id'],'is_deleted' => 0))->count();
            $agent_info['trademarkCount'] = $count;
            $this->assign("agentinfo",$agent_info);
        }
        $this->display();
    }

    /**
     * 退出
     */
    public function logout(){
        session('member',null);
        header('Location:/');
    }

    /**
     * 账户绑定手机号
     */
    public function bindmobile(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('请先登录');
        }
        $member = session('member');
        $case = $this->_get("case");
        $mobile = $this->_post("mobile");
        if( empty($mobile) ){
            $this->ajaxError('手机号码不能为空！');
        }
        if(!preg_match('/^1[3-9]\d{9}$/', $mobile)){
            $this->ajaxError('手机号码格式不正确！');
        }
        //检查是否允许绑定
        $adminUser = M('admin_user')->where(array('user_mobile' => $mobile,'is_deleted' => 0))->find();
        if( !empty($adminUser) && $adminUser['id'] != $member['id'] ){
            $this->ajaxError('手机号已绑定其他账户，请更换手机号！');
        }
        if( !empty($adminUser) && $adminUser['id'] == $member['id'] ){
            $this->ajaxError('当前账户已绑定该手机号，无需重复绑定！');
        }
        $verifyKey = 'verify.bind.'.$mobile;
        //发送手机绑定验证码
        if( $case == 'sendsmscode' ){
            import('@.ORG.Juhe.Juhe');
            $verifyCode = rand(1000,9999);
            $result = Juhe::sendSms("smsCode", $mobile, ["code"=>$verifyCode]);
            if ($result['status'] == 1) {
                S($verifyKey, $verifyCode,300);
                $this->ajaxSuccess("验证码发送成功");
            } else {
                $this->ajaxError("验证码发送失败！" + $result['message']);
            }
        }elseif($case == 'bind'){
            $verify = $this->_post("verify");
            if( $verify != S($verifyKey) ){
                $this->ajaxError("验证码不正确");
            }
            $F = M('admin_user')->where(array('id' => $member['id'],'is_deleted' => 0))->save(array('user_mobile'=>$mobile,'updated_at'=>date('Y-m-d H:i:s')));
            if ($F == true) {
                S($verifyKey,null);
                //刷新session
                $member['user_mobile'] = $mobile;
                session('member', $member);
                $this->ajaxSuccess("绑定成功！");
            } else {
                $this->ajaxError("绑定失败！");
            }
        }
    }

    /**
     * 设置加价幅度
     */
    public function setplusprice(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('请先登录');
        }
        $this->ajaxSuccess("无权限访问！");
        $member = session('member');
        $plus_price = intval($this->_post("plus_price"));
        if( $plus_price < 0 || $plus_price > 99999 ){
            $this->ajaxError("加价幅度请控制在0-99999之间！");
        }
        if( $member['role_id'] != 3 ){
            $this->ajaxError("角色不正确，只允许代理进行加价幅度调增！");
        }
        $F = M('admin_agent_info')->where(array('admin_id' => $member['id']))->save(array('plus_price'=>$plus_price,'updated_at'=>date('Y-m-d H:i:s')));
        if ($F == true) {
            $this->ajaxSuccess("设置成功！");
        } else {
            $this->ajaxError("设置失败！");
        }
    }

    /**
     * 代理人员管理
     */
    public function agentusers(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->error_notice("权限不足！禁止进行访问！");
        }
        //查询代理人员列表
        $agentusers = M("admin_user as u")
            ->field("u.role_name, u.user_pwd, u.user_name,u.user_mobile,u.disabled_status,u.status,ai.id as agent_id, ai.admin_id,ai.agent_sn,ai.id_card_check_status,ai.id_card_name,ai.id_card_number,ai.id_card_front_image,ai.id_card_back_image,ai.plus_price,ai.created_at")
            ->join("admin_agent_info as ai on u.id = ai.admin_id")
            ->where(array('u.role_id' => 3,'u.is_deleted' => 0))
            ->select();
        foreach ($agentusers as $key => $val) {
            //查询代理的商标总数
            $count = M("trademarks")->where(array("agent_id"=>$val['agent_id'], 'status'=>1, 'is_deleted' => 0))->count();
            $agentusers[$key]['trademarkCount'] = empty($count) ? 0 : $count;
            if( $agentusers[$key]['user_pwd'] != $this->gen_password(C('INIT_PASSWPRD')) ){
                $agentusers[$key]['resetpwd'] = 1;
            }
        }
        $this->assign("agentusers",$agentusers);
        $this->display();
    }

    /**
     * 重置代理员工密码
     */
    public function resetagentuserpwd(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->ajaxError("权限不足，只允许管理员以上权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $arr = explode('_',$post['unionsn']);
        if( count($arr) != 2 ){
            $this->ajaxError("参数不正确！");
        }
        $agent_sn = intval($arr[0]);
        $admin_id = intval($arr[1]);
        if( $agent_sn == 0 || $admin_id == 0 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->find();
        $agentuser = M("admin_agent_info")->where(array('admin_id'=>$admin_id,'agent_sn'=>$agent_sn))->find();
        if( empty($adminuser) || empty($agentuser) ){
            $this->ajaxError("代理不存在！");
        }
        //进行密码重置
        $save = array();
        $save['user_pwd'] = $this->gen_password(C('INIT_PASSWPRD'));
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->save($save);
        if ($F == true) {
            $this->ajaxSuccess("密码重置成功！");
        } else {
            $this->ajaxError("密码重置失败！");
        }
    }

    /**
     * 设置代理账户的【禁用、启用】状态
     */
    public function changeaccountstatus(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->ajaxError("权限不足，只允许管理员以上权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $arr = explode('_',$post['unionsn']);
        if( count($arr) != 3 ){
            $this->ajaxError("参数不正确！");
        }
        $agent_sn = intval($arr[0]);
        $admin_id = intval($arr[1]);
        $agent_cur_status = intval($arr[2]);
        if( $agent_sn == 0 || $admin_id == 0 || mb_strlen($agent_cur_status) != 1 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->find();
        $agentuser = M("admin_agent_info")->where(array('admin_id'=>$admin_id,'agent_sn'=>$agent_sn))->find();
        if( empty($adminuser) || empty($agentuser) ){
            $this->ajaxError("代理不存在！");
        }
        if( $agent_cur_status != $adminuser['disabled_status'] ){
            $this->ajaxError("代理账户当前状态异常！");
        }
        //进行禁用启用操作
        $save = array();
        $save['disabled_status'] = ($agent_cur_status == 1) ? 0 : 1;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->save($save);
        if ($F == true) {
            $this->ajaxSuccess(($agent_cur_status == 1) ? "启用成功！" : "禁用成功！");
        } else {
            $this->ajaxError(($agent_cur_status == 1) ? "启用失败！" : "禁用失败！");
        }
    }

    //删除代理账户
    public function delagentuser(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1)) ){
            $this->ajaxError("权限不足，只超级管理员权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $arr = explode('_',$post['unionsn']);
        if( count($arr) != 2 ){
            $this->ajaxError("参数不正确！");
        }
        $agent_sn = intval($arr[0]);
        $admin_id = intval($arr[1]);
        if( $agent_sn == 0 || $admin_id == 0 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->find();
        $agentuser = M("admin_agent_info")->where(array('admin_id'=>$admin_id,'agent_sn'=>$agent_sn))->find();
        if( empty($adminuser) || empty($agentuser) ){
            $this->ajaxError("代理不存在！");
        }
        //开启事务
        D('Common')->startTrans();
        try {
            $where = array();
            $where['agent_id'] = $agentuser["id"];
            $where['is_deleted'] = 0;
            $list = M("trademarks")->where($where)->select();
            if( !empty($list) ){
                $F = M("trademarks")->where($where)->delete();
                if (!$F) {
                    throw new Exception("删除代理商标信息失败！");
                }
            }
            $R = M("admin_agent_info")->where(array('id'=>$agentuser["id"]))->delete();
            if (!$R) {
                throw new Exception("代理拓展信息删除失败！");
            }
            $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted' => 0))->delete();
            if (!$F) {
                throw new Exception("代理删除失败！");
            }
            D('Common')->commit();
            $this->ajaxSuccess("代理删除成功！");
        }catch (Exception $e) {
            D('Common')->rollback();
            $this->ajaxError($e->getMessage());
        }
    }

    /**
     * 添加代理
     */
    public function addagentuser(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->ajaxError("权限不足，只允许管理员以上权限操作！");
        }
        $post = $this->boxpost();
        $username = trim($post['username']);
        $usermobile = trim($post['usermobile']);
        if( empty($username) ){
            $this->ajaxError('用户名不能为空！');
        }
        if( mb_strlen($username) < 4 || mb_strlen($username) > 15 ){
            $this->ajaxError('用户名请控制在4-15个字符以内！');
        }
        if( empty($usermobile) ){
            $this->ajaxError('手机号码不能为空！');
        }
        if(!preg_match('/^1[3-9]\d{9}$/', $usermobile)){
            $this->ajaxError('手机号码格式不正确！');
        }
        //查询用户基础信息
        $checkUsername = M("admin_user")->where(array('user_name' => $username, 'is_deleted' => 0))->find();
        if( $checkUsername ){
            $this->ajaxError('用户名已存在！');
        }
        $checkMobile = M("admin_user")->where(array('user_mobile' => $usermobile, 'is_deleted' => 0))->find();
        if( $checkMobile ){
            $this->ajaxError('手机号码已存在！');
        }
        //获取加密密码
        $initpasswd = $this->gen_password(C("INIT_PASSWPRD"));
        //开启事务
        D('Common')->startTrans();
        try {
            //增加代理商户
            $adminUser = array();
            $adminUser['role_id'] = 3;
            $adminUser['role_name'] = "代理";
            $adminUser['user_name'] = $username;
            $adminUser['user_mobile'] = $usermobile;
            $adminUser['user_pwd'] = $initpasswd;
            $adminUser['disabled_status'] = 0;
            $adminUser['status'] = 1;
            $adminUser['created_at'] = $this->now;
            $F = M("admin_user")->add($adminUser);
            if (!$F) {
                throw new Exception("添加代理基本信息失败！" . M("admin_user")->_sql());
            }
            $adminId = M("admin_user")->getLastInsID();
            //添加代理商拓展信息
            $agentSn = $adminId + 1000000;
            $adminAgentInfo = array();
            $adminAgentInfo['agent_sn'] = $agentSn;
            $adminAgentInfo['admin_id'] = $adminId;
            $adminAgentInfo['id_card_check_status'] = 0;
            $adminAgentInfo['plus_price'] = 0;
            $adminAgentInfo['created_at'] = $this->now;
            $F = M("admin_agent_info")->add($adminAgentInfo);
            if (!$F) {
                throw new Exception("添加代理拓展信息失败！" . M("admin_agent_info")->_sql() );
            }
            D('Common')->commit();
            $this->ajaxSuccess(("添加成功，代理编号：【".$agentSn."】，密码：【".C("INIT_PASSWPRD")."】！"));
        }catch (Exception $e) {
            D('Common')->rollback();
            $this->ajaxError($e->getMessage());
        }
    }

    /**
     * 设置代理账户的实名认证状态
     */
    public function checkagentidcardstatus(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->ajaxError("权限不足，只允许管理员以上权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $arr = explode('_',$post['unionsn']);
        if( count($arr) != 2 ){
            $this->ajaxError("参数不正确！");
        }
        $agent_sn = intval($arr[0]);
        $admin_id = intval($arr[1]);
        if( $agent_sn == 0 || $admin_id == 0 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>3, 'is_deleted'=>0))->find();
        $agentuser = M("admin_agent_info")->where(array('admin_id'=>$admin_id,'agent_sn'=>$agent_sn))->find();
        if( empty($adminuser) || empty($agentuser) ){
            $this->ajaxError("代理不存在！");
        }
        if( $agentuser['id_card_check_status'] != 1){
            $this->ajaxError("代理账户非待审核状态，暂时不支持审核！");
        }
        $checkremark = trim($post['check_remark']);
        $status = intval($post['checkstatus']);
        if( $status != 2 && $status != 3 ){
            $this->ajaxError("审核状态参数不正确！");
        }
        if( $status == 3 && empty($checkremark)){
            $this->ajaxError("拒绝通过，请补充拒绝原因！");
        }
        if( !empty($checkremark) && (mb_strlen($checkremark) < 4 || mb_strlen($checkremark) > 20) ){
            $this->ajaxError("拒绝原因请控制在4-20个字符！".mb_strlen($checkremark));
        }
        //进行审核操作
        $save = array();
        $save['id_card_check_status'] = $status;
        $save['id_card_check_remark'] = $checkremark;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_agent_info")->where(array('id'=>$agentuser['id']))->save($save);
        if ($F == true) {
            $this->ajaxSuccess("审核成功！");
        } else {
            $this->ajaxError("审核失败！");
        }
    }

    /**
     * 管理员管理
     */
    public function adminusers(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        if( !in_array($this->member['role_id'],array(1)) ){
            $this->error_notice("权限不足！禁止进行访问！");
        }
        //查询管理员列表
        $adminusers = M("admin_user as u")
            ->field("u.id as admin_id,u.role_name, u.user_pwd, u.user_name, u.user_mobile, u.disabled_status, u.wechat_work_id, u.status, u.created_at")
            ->where(array('u.role_id' => 2,'u.is_deleted' => 0))
            ->select();
        foreach ($adminusers as $key => $val) {
            if( $adminusers[$key]['user_pwd'] != $this->gen_password(C('INIT_PASSWPRD')) ){
                $adminusers[$key]['resetpwd'] = 1;
            }
        }
        $this->assign("adminusers",$adminusers);
        $this->display();
    }

    /**
     * 添加管理员
     */
    public function addadminuser(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1)) ){
            $this->ajaxError("权限不足，只允许超管权限操作！");
        }
        $post = $this->boxpost();
        $username = trim($post['username']);
        $usermobile = trim($post['usermobile']);
        if( empty($username) ){
            $this->ajaxError('用户名不能为空！');
        }
        if( mb_strlen($username) < 4 || mb_strlen($username) > 15 ){
            $this->ajaxError('用户名请控制在4-15个字符以内！');
        }
        if( empty($usermobile) ){
            $this->ajaxError('手机号码不能为空！');
        }
        if(!preg_match('/^1[3-9]\d{9}$/', $usermobile)){
            $this->ajaxError('手机号码格式不正确！');
        }
        //查询用户基础信息
        $checkUsername = M("admin_user")->where(array('user_name' => $username, 'is_deleted' => 0))->find();
        if( $checkUsername ){
            $this->ajaxError('用户名已存在！');
        }
        $checkMobile = M("admin_user")->where(array('user_mobile' => $usermobile, 'is_deleted' => 0))->find();
        if( $checkMobile ){
            $this->ajaxError('手机号码已存在！');
        }
        //获取加密密码
        $initpasswd = $this->gen_password(C("INIT_PASSWPRD"));
        //开启事务
        D('Common')->startTrans();
        try {
            //增加管理员账号
            $adminUser = array();
            $adminUser['role_id'] = 2;
            $adminUser['role_name'] = "管理员";
            $adminUser['user_name'] = $username;
            $adminUser['user_mobile'] = $usermobile;
            $adminUser['user_pwd'] = $initpasswd;
            $adminUser['disabled_status'] = 0;
            $adminUser['status'] = 1;
            $adminUser['created_at'] = $this->now;
            $F = M("admin_user")->add($adminUser);
            if (!$F) {
                throw new Exception("添加管理员信息失败！");
            }
            D('Common')->commit();
            $this->ajaxSuccess(("添加成功，管理员编号：【".M("admin_user")->getLastInsID()."】，密码：【".C("INIT_PASSWPRD")."】！"));
        }catch (Exception $e) {
            D('Common')->rollback();
            $this->ajaxError($e->getMessage());
        }
    }

    /**
     * 修改管理员的启用禁用状态
     */
    public function changeadminaccountstatus(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1)) ){
            $this->ajaxError("权限不足，只允许超管权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $arr = explode('_',$post['unionsn']);
        if( count($arr) != 2 ){
            $this->ajaxError("参数不正确！");
        }
        $admin_id = intval($arr[0]);
        $admin_cur_status = intval($arr[1]);
        if( $admin_id == 0 || mb_strlen($admin_cur_status) != 1 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->find();
        if( empty($adminuser) ){
            $this->ajaxError("代理不存在！");
        }
        if( $admin_cur_status != $adminuser['disabled_status'] ){
            $this->ajaxError("管理员账户当前状态异常！");
        }
        //进行禁用启用操作
        $save = array();
        $save['disabled_status'] = ($admin_cur_status == 1) ? 0 : 1;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->save($save);
        if ($F == true) {
            $this->ajaxSuccess(($admin_cur_status == 1) ? "启用成功！" : "禁用成功！");
        } else {
            $this->ajaxError(($admin_cur_status == 1) ? "启用失败！" : "禁用失败！");
        }
    }

    /**
     * 重置代理员工密码
     */
    public function resetadminuserpwd(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->ajaxError("权限不足，只允许管理员及以上权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $admin_id = intval($post['unionsn']);
        if( $admin_id == 0 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->find();
        if( empty($adminuser) ){
            $this->ajaxError("管理员不存在！");
        }
        //进行密码重置
        $save = array();
        $save['user_pwd'] = $this->gen_password(C('INIT_PASSWPRD'));
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->save($save);
        if ($F == true) {
            $this->ajaxSuccess("密码重置成功！");
        } else {
            $this->ajaxError("密码重置失败！");
        }
    }

    /**
     * 删除管理员
     */
    public function deladminuser(){
        if ($this->checkLogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录');
        }
        if( !in_array($this->member['role_id'],array(1)) ){
            $this->ajaxError("权限不足，只允许超管权限操作！");
        }
        $post = $this->boxpost();
        if( !isset($post['unionsn']) || empty($post['unionsn']) ){
            $this->ajaxError("参数不正确！");
        }
        $admin_id = intval($post['unionsn']);
        if( $admin_id == 0 ){
            $this->ajaxError("参数不正确！");
        }
        $adminuser = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->find();
        if( empty($adminuser) ){
            $this->ajaxError("管理员不存在！");
        }
        //进行删除
        $save = array();
        $save['is_deleted'] = 1;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("admin_user")->where(array('id'=>$admin_id,'role_id'=>2, 'is_deleted'=>0))->save($save);
        if ($F == true) {
            $this->ajaxSuccess("删除成功！");
        } else {
            $this->ajaxError("删除失败！");
        }
    }

    /**
     * 修改密码
     */
    public function changepwd(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        $this->display();
    }

    /**
     * 提交密码修改
     */
    public function modifypasswordsubmit()
    {
        if (!$this->checkLogin(true)) {
            $this->ajaxError('请先登录再操作');
        }
        $oldpwd = $this->_post('oldpwd');
        $newpwd = $this->_post('newpwd');
        $confirmpwd = $this->_post('confirmpwd');
        if ($this->gen_password($oldpwd) != $this->member['user_pwd']) {
            $this->ajaxError('老密码不正确'.$oldpwd.'='.$this->gen_password($oldpwd)."==".$this->member['user_pwd']);
        }
        if ($newpwd != $confirmpwd || mb_strlen($newpwd) < 6) {
            $this->ajaxError('两次新密码必须一致并且不小于6个字符');
        }
        if( $newpwd == $oldpwd ){
            $this->ajaxError('新密码需与老密码不同！');
        }
        $save = array('user_pwd' => $this->gen_password($newpwd),'updated_at'=>$this->now);
        $F = M('admin_user')->where(array('id' => $this->member['id']))->save($save);
        if ( !$F ) {
            $this->ajaxError("修改失败，请重试或联系客服");
        }
        session("member",null);
        $this->ajaxSuccess('修改成功，请重新登录');
    }

    /**
     * 线索管理
     */
    public function cluesmanage(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->error_notice("仅对管理员及以上角色开放，暂无权限！");
        }
        $ac = $this->_get('ac', 'trim', '');
        $starttime = $this->_get('ts', 'trim', '');
        $endtime = $this->_get('te', 'trim', '');
        $culesId = $this->_get('culesId', 'intval', 0);
        $culesSource = $this->_get('culesSource', 'trim', '');
        $culesStatus = $this->_get('culesStatus', 'trim', '');
        $where = array();
        $where['status'] = 1;
        $params = '';
        if ($starttime) {
            $params .= '/ts/' . $starttime;
            $where['created_at'] = array('egt',$starttime);
        }
        if ($endtime) {
            $params .= '/te/' . $endtime;
            $where['created_at'] = array('elt',$endtime);
        }
        if( $culesId > 0 ){
            $params .= '/culesId/' . $culesId;
            $where['id'] = $culesId;
        }
        if ($culesSource != '') {
            $params .= '/culesSource/' . $culesSource;
            $where['source'] = $culesSource;
        }
        if ($culesStatus != '') {
            $params .= '/culesStatus/' . $culesStatus;
            if( intval($culesStatus) == 1 ){
                $where['handle_status'] = 0;
            }
            if( intval($culesStatus) == 2 ){
                $where['handle_status'] = 1;
            }
        }
        //渠道枚举
        $sourceArr = C('CLUES_SOURCE');
        //导出操作
        if( $ac == 'export' ){
            $filename = "线索管理";
            $titles = array(
                array("name"=>"编号","cellWidth" => 10),
                array("name"=>"渠道","cellWidth" => 15.5),
                array("name"=>"联系方式","cellWidth" => 15),
                array("name"=>"商标编号","cellWidth" => 10),
                array("name"=>"商标名称","cellWidth" => 20),
                array("name"=>"商标报价","cellWidth" => 15),
                array("name"=>"IP地址","cellWidth" => 15),
                array("name"=>"状态","cellWidth" => 15),
                array("name"=>"创建时间","cellWidth" => 20),
                array("name"=>"备注","cellWidth" => 20),
            );
            $clueslist = M("user_clues")->where($where)->order('created_at DESC')->select();
            foreach ( $clueslist as $k => $v ) {
                $temp = [
                    $v['id'],
                    $sourceArr[$v['source']],
                    $v['mobile'],
                    $v['trademark_sn'],
                    $v['trademark_name'],
                    $v['trademark_price'],
                    $v['ip'],
                    ( ( $v['handle_status'] == 0 ) ? '待处理' : '已处理' ),
                    $v['created_at'],
                    $v['remark']
                ];
                $datalist[] = $temp;
            }
            $this->exportExcel($titles, $datalist, $filename, "线索列表");
            exit();
        }else{
            $this->M->page['no'] = $this->_get('p') ? $this->_get('p', 'intval') : 1;
            $this->M->page['num'] = 10;
            $this->M->page['total'] = ceil(M()->table("user_clues")->where($where)->count() / $this->M->page['num']);
            $clueslist = M("user_clues")
                ->where($where)
                ->order('created_at DESC')
                ->limit($this->page_limit())
                ->select();
            foreach ( $clueslist as $k => $v ) {
                $clueslist[$k]['source_text'] = $sourceArr[$v['source']];
            }
            $pageurl = '/member/cluesmanage' . $params . '/p/*.html';
            $this->set_pages($pageurl);
            $this->assign('sourcelist', $sourceArr);
            if( $culesId > 0 ){
                $this->assign('culesId', $culesId);
            }
            $this->assign('culesStatus', $culesStatus);
            $this->assign('culesSource', $culesSource);
            $this->assign('clueslist', $clueslist);
            $this->display();
        }
    }

    /**
     * 更改线索处理状态
     */
    public function setcluesHandleStatus(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->error_notice("仅对管理员及以上角色开放，暂无权限！");
        }
        $data = $this->boxpost();
        $id = intval($data['id']);
        $where = array();
        $where['status'] = 1;
        $where['id'] = $id;
        $clue = M("user_clues")->where($where)->find();
        if( empty($clue) ){
            $this->ajaxError('线索不存在，请确认后在处理！');
        }
        if( $clue['handle_status'] == 1 ){
            $this->ajaxError('线索已处理，不能重复处理！');
        }
        $save = array();
        $save['handle_status'] = 1;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("user_clues")->where($where)->save($save);
        if( !$F ){
            $this->ajaxError('线索处理失败！');
        }
        $this->ajaxSuccess('线索处理成功！');
    }

    /**
     * 商标管理（超管）
     */
    public function trademarksmanage(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->error_notice("仅对管理员及以上角色开放，暂无权限！");
        }
        $ac = $this->_get('ac', 'trim', '');
        $starttime = $this->_get('ts', 'trim', '');
        $endtime = $this->_get('te', 'trim', '');
        $agentId = $this->_get('agentId', 'trim', '');
        $saleStatus = $this->_get('saleStatus', 'trim', '');
        $imageStatus = $this->_get('imageStatus', 'trim', '');
        $trademarkSn = $this->_get('trademarkSn', 'trim', '');
        $trademarkStatus = $this->_get('trademarkStatus', 'trim', '');
        //构造搜索条件
        $where = array();
        $where['is_deleted'] = 0;
        $params = '';
        if ($starttime) {
            $params .= '/ts/' . $starttime;
            $where['created_at'] = array('egt',$starttime." 00:00:00");
        }
        if ($endtime) {
            $params .= '/te/' . $endtime;
            $where['created_at'] = array('elt',$endtime." 23:59:59");
        }
        if ($trademarkSn != '') {
            $params .= '/trademarkSn/' . $trademarkSn;
            $where['trademark_sn'] = $trademarkSn;
        }
        if( $agentId != '' ){
            $params .= '/agentId/' . $agentId;
            $where['agent_id'] = $agentId;
        }
        if ($trademarkStatus != '') {
            $params .= '/trademarkStatus/' . $trademarkStatus;
            if( intval($trademarkStatus) == 0 ){
                $where['status'] = 0;
            }
            if( intval($trademarkStatus) == 1 ){
                $where['status'] = 1;
            }
            if( intval($trademarkStatus) == 2 ){
                $where['status'] = 2;
            }
        }
        if ($saleStatus != '') {
            $params .= '/saleStatus/' . $saleStatus;
            if( intval($saleStatus) == 0 ){
                $where['sale_status'] = 0;
            }
            if( intval($saleStatus) == 1 ){
                $where['sale_status'] = 1;
            }
        }
        if ( $imageStatus != '' ){
            $params .= '/imageStatus/' . $imageStatus;
            if( intval($imageStatus) == 0 ){
                $where['thumb_image'] = '';
            }
            if( intval($imageStatus) == 1 ){
                $where['thumb_image'] = array('neq','');
            }
        }
        //导出操作
        if( $ac == 'export' ){
            $filename = '商标列表-' . date('YmdHis');
            $titles = array(
                array("name"=>"序号","cellWidth" => 10),
                array("name"=>"商标名","cellWidth" => 15),
                array("name"=>"类别","cellWidth" => 10),
                array("name"=>"价格(元)","cellWidth" => 15),
                array("name"=>"商标号","cellWidth" => 15),
                array("name"=>"代理","cellWidth" => 15),
                array("name"=>"产品/服务","cellWidth" => 40),
                array("name"=>"群组","cellWidth" => 25),
                array("name"=>"注册日期","cellWidth" => 15),
                array("name"=>"备注","cellWidth" => 15),
            );
            $agentUserName = array();
            $agents = M("admin_agent_info ai")->join("admin_user u on ai.admin_id = u.id")->field("ai.id,u.user_name")->select();
            if( !empty($agents) ){
                foreach ($agents as $k => $v){
                    if( !isset($agentUserName[$v['id']]) ){
                        $agentUserName[$v['id']] = $v['user_name'];
                    }
                }
            }
            //初始化内容数组
            $datalist = array();
            $trademarklist = M("trademarks")
                ->where($where)
                ->order('updated_at DESC, id desc')
                ->limit(10000)
                ->select();
            foreach ( $trademarklist as $k => $v ) {
                //查询代理信息
                $agentname = isset( $agentUserName[$v['agent_id']] ) ? $agentUserName[$v['agent_id']] : "";
                $group_sn = array();
                $goods_chinese_name = array();
                if( !empty($v['trademark_group_sn']) ){
                    $group_sn = json_decode($v['trademark_group_sn'],true);
                }
                if( !empty($v['trademark_goods_name']) ){
                    $goods_chinese_name_json = json_decode($v['trademark_goods_name'],true);
                    if( !empty($goods_chinese_name_json) ){
                        foreach ($goods_chinese_name_json as $key => $value){
                            for ( $i = 0; $i < count($value); $i++ ){
                                if( !in_array($value[$i],$goods_chinese_name) ){
                                    array_push($goods_chinese_name,$value[$i]);
                                }
                            }
                        }
                    }
                }
                $temp = [
                    ( $k + 1 ),
                    $v['trademark_name'],
                    $v['trademark_cate'],
                    $v['trademark_price'],
                    $v['trademark_sn'],
                    $agentname,
                    empty($goods_chinese_name) ? "" : join("；",$goods_chinese_name),
                    empty($group_sn) ? "" : join("；",$group_sn),
                    ( !empty($v['trademark_registered_time']) && $v['trademark_registered_time'] != '0000-00-00' ) ? msubstr($v['trademark_registered_time'],0,10) : "",
                    $v['remark']
                ];
                $datalist[] = $temp;
            }
            $this->exportExcel($titles, $datalist, $filename, "商标列表");
            exit();
        }else {
            $this->M->page['no'] = $this->_get('p') ? $this->_get('p', 'intval') : 1;
            $this->M->page['num'] = 10;
            $this->M->page['total'] = ceil(M("trademarks")->where($where)->count() / $this->M->page['num']);
            $trademarklist = M("trademarks")
                ->where($where)
                ->order('updated_at DESC, id desc')
                ->limit($this->page_limit())
                ->select();
            foreach ( $trademarklist as $k => $v ) {
                //查询代理信息
                $agentInfo = M("admin_agent_info")->where(array('id' => $v['agent_id']))->find();
                if( !empty($agentInfo) ){
                    $admin = M("admin_user")->where(array('id' => $agentInfo['admin_id']))->find();
                    $trademarklist[$k]['user_name'] = $admin['user_name'];
                    $trademarklist[$k]['user_mobile'] = $admin['user_mobile'];
                }
            }
            $agentlist = M("admin_agent_info a")
                ->join("admin_user u on a.admin_id = u.id")
                ->where(['u.is_deleted' => 0])
                ->field("a.agent_sn, a.id, u.user_name")
                ->select();
            $pageurl = '/member/trademarksmanage' . $params . '/p/*.html';
            $this->set_pages($pageurl);
            $this->assign('saleStatus', $saleStatus);
            $this->assign('agentlist', $agentlist);
            $this->assign('trademarkSn', $trademarkSn);
            $this->assign('trademarkStatus', $trademarkStatus);
            $this->assign('imageStatus', $imageStatus);
            $this->assign('agentId', $agentId);
            $this->assign('trademarklist', $trademarklist);
            $this->display();
        }
    }

    /**
     * 删除商标
     */
    public function deltrademark(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        $id = intval($this->_post('id'));
        $where = array();
        $where['id'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks")->where($where)->find();
        if( empty($trademark) ){
            $this->ajaxError('商标信息不存在，请确认后在处理！');
        }
        $save = array();
        $save['is_deleted'] = 1;
        $save['deleted_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks")->where($where)->save($save);
        if( !$F ){
            $this->ajaxError('商标删除失败！');
        }
        $this->ajaxSuccess('商标删除成功！');
    }

    /**
     * 重新生成缩略图
     */
    public function resetColorImage(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        if( !in_array($this->member['role_id'],array(1,2)) ){
            $this->error_notice("仅对管理员及以上角色开放，暂无权限！");
        }
        $id = intval($this->_post('id'));
        $where = array();
        $where['id'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks")->where($where)->find();
        if( empty($trademark) ){
            $this->ajaxError('商标信息不存在！');
        }
        if( empty($trademark['trademark_image']) || $this->checkRemoteFile($trademark['trademark_image']) != true ){
            $this->ajaxError('商标原图不存在！');
        }
        import('@.ORG.Util.ImageCutUtil');
        $year = 1000;
        $savePath = UPLOAD_PATH. "thumb-image" . DIRECTORY_SEPARATOR. $year;
        $filename = $trademark['trademark_sn'].".jpg";
        $resource = $savePath.DIRECTORY_SEPARATOR.$filename;
        //完整图片路径
        if( file_exists($resource) == true ){
            //删除图片
            if( unlink($resource) == false ){
                $this->ajaxError('移除原图失败！');
            }
        }
        $thumbImageUrl = $this->createGoodsThumbImage($trademark['trademark_image'], $filename, $savePath, 0, 0, true);
        if( $thumbImageUrl != null ){
            //数据库存储路径
            $thumbImageUrl = "/Upload/thumb-image".DIRECTORY_SEPARATOR.$year.DIRECTORY_SEPARATOR.$filename;
            //对图片进行裁剪
            if( file_exists($resource) == true ){
                $imageCutUtil = new ImageCutUtil();
                $imageCutUtil->cut($resource, $resource, false, 250);
            }else{
                $this->ajaxError('缩略图不存在！');
            }
        }else{
            $this->ajaxError('图片重置失败！');
        }
        $save = array();
        $save['thumb_image'] = $thumbImageUrl;
        $save['updated_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks")->where($where)->save($save);
        if( !$F ){
            $this->ajaxError('图片重置成功，但保存图片路径失败！');
        }
        $this->ajaxSuccess('图片重置成功！');
    }

    /**
     * 商标管理（代理）
     */
    public function trademarksselfmanage(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        if( !in_array($this->member['role_id'],array(3)) ){
            $this->error_notice("仅对代理角色开放，暂无权限！");
        }
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }
        $ac = $this->_get('ac', 'trim', '');
        $starttime = $this->_get('ts', 'trim', '');
        $endtime = $this->_get('te', 'trim', '');
        $saleStatus = $this->_get('saleStatus', 'trim', '');
        $trademarkSn = $this->_get('trademarkSn', 'trim', '');
        $trademarkStatus = $this->_get('trademarkStatus', 'trim', '');
        //构造搜索条件
        $where = array();
        $where['is_deleted'] = 0;
        $where['agent_id'] = $memberAgentInfo['id'];
        $params = '';
        if ($starttime) {
            $params .= '/ts/' . $starttime;
            $where['created_at'] = array('egt',$starttime." 00:00:00");
        }
        if ($endtime) {
            $params .= '/te/' . $endtime;
            $where['created_at'] = array('elt',$endtime." 23:59:59");
        }
        if ($trademarkSn != '') {
            $params .= '/trademarkSn/' . $trademarkSn;
            $where['trademark_sn'] = $trademarkSn;
        }
        if ($trademarkStatus != '') {
            $params .= '/trademarkStatus/' . $trademarkStatus;
            if( intval($trademarkStatus) == 0 ){
                $where['status'] = 0;
            }
            if( intval($trademarkStatus) == 1 ){
                $where['status'] = 1;
            }
            if( intval($trademarkStatus) == 2 ){
                $where['status'] = 2;
            }
        }
        if ($saleStatus != '') {
            $params .= '/saleStatus/' . $saleStatus;
            if( intval($saleStatus) == 0 ){
                $where['sale_status'] = 0;
            }
            if( intval($saleStatus) == 1 ){
                $where['sale_status'] = 1;
            }
        }
        //导出操作
        if( $ac == 'export' ){
            $filename = '我的商标-' . date('YmdHis');
            $titles = array(
                array("name"=>"序号","cellWidth" => 10),
                array("name"=>"图样","cellWidth" => 15.5),
                array("name"=>"商标名","cellWidth" => 15),
                array("name"=>"类别","cellWidth" => 10),
                array("name"=>"价格(元)","cellWidth" => 15),
                array("name"=>"商标号","cellWidth" => 15),
                array("name"=>"产品/服务","cellWidth" => 40),
                array("name"=>"群组","cellWidth" => 25),
                array("name"=>"注册日期","cellWidth" => 15),
                array("name"=>"备注","cellWidth" => 15),
            );
            $trademarklist = M("trademarks")
                ->field("trademark_sn,trademark_image,thumb_image,trademark_name,trademark_cate,trademark_price,trademark_registered_time,trademark_group_sn,trademark_goods_name,remark")
                ->where($where)
                ->order('updated_at DESC, id desc')
                ->limit(50)
                ->select();
            foreach ( $trademarklist as $k => $v ) {
                $group_sn = array();
                $goods_chinese_name = array();
                if( !empty($v['trademark_group_sn']) ){
                    $group_sn = json_decode($v['trademark_group_sn'],true);
                }
                if( !empty($v['trademark_goods_name']) ){
                    $goods_chinese_name_json = json_decode($v['trademark_goods_name'],true);
                    if( !empty($goods_chinese_name_json) ){
                        foreach ($goods_chinese_name_json as $key => $value){
                            for ( $i = 0; $i < count($value); $i++ ){
                                if( !in_array($value[$i],$goods_chinese_name) ){
                                    array_push($goods_chinese_name,$value[$i]);
                                }
                            }
                        }
                    }
                }
                $temp = [
                    ( $k + 1 ),
                    empty($v['thumb_image']) ? $v['trademark_image'] : "http://web.dunmama.cn" . $v['thumb_image'],
                    $v['trademark_name'],
                    $v['trademark_cate'],
                    $v['trademark_price'],
                    $v['trademark_sn'],
                    empty($goods_chinese_name) ? "" : join("；",$goods_chinese_name),
                    empty($group_sn) ? "" : join("；",$group_sn),
                    ( !empty($v['trademark_registered_time']) && $v['trademark_registered_time'] != '0000-00-00' ) ? msubstr($v['trademark_registered_time'],0,10) : "",
                    $v['remark']
                ];
                $datalist[] = $temp;
            }
            $this->exportExcel($titles, $datalist, $filename, "我的商标");
            exit();
        }else {
            $this->M->page['no'] = $this->_get('p') ? $this->_get('p', 'intval') : 1;
            $this->M->page['num'] = 10;
            $this->M->page['total'] = ceil(M("trademarks")->where($where)->count() / $this->M->page['num']);
            $trademarklist = M("trademarks")
                ->where($where)
                ->order('updated_at DESC, id desc')
                ->limit($this->page_limit())
                ->select();
            $pageurl = '/member/trademarksselfmanage' . $params . '/p/*.html';
            $this->set_pages($pageurl);
            $this->assign('saleStatus', $saleStatus);
            $this->assign('trademarkSn', $trademarkSn);
            $this->assign('trademarkStatus', $trademarkStatus);
            $this->assign('trademarklist', $trademarklist);
            $this->display();
        }
    }

    /**
     * 批量操作V2.0
     */
    public function trademarksbatchhandle(){
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }
        $ac = $this->_get('ac', 'trim', '');
        if( $ac == "setting" ){
            $batchAction = $this->_post("action");
            if( $batchAction != "status" && $batchAction != "saleStatus" ){
                $this->ajaxError('操作类型不正确！');
            }
            $trademarkSn = $this->_post("trademarkSn","trim");
            if( empty($trademarkSn) ){
                $this->ajaxError('请输入商标编号！');
            }
            $trademarkSn = explode("\n",$trademarkSn);
            $trademarkIds = array();
            for ($i = 0; $i < count($trademarkSn); $i++){
                $sn = trim($trademarkSn[$i]);
                if( !empty($sn) ){
                    //查询是否属于当前代理商；
                    $where = array();
                    $where['trademark_sn'] = $sn;
                    $where['agent_id'] = $memberAgentInfo["id"];
                    $where['is_deleted'] = 0;
                    $list = M("trademarks")->where($where)->select();
                    if( empty($list) ){
                        //$this->ajaxError("当前代理商下未检测到该商标：{$sn}！");
                        continue;
                    }
                    foreach ( $list as $k => $v ){
                        array_push($trademarkIds, $v['id']);
                    }
                }
            }
            if( count($trademarkIds) == 0 ){
                $this->ajaxError('未匹配出需要操作的商标！');
            }
            $where = array();
            $where['id'] = ["in",$trademarkIds];
            $where['agent_id'] = $memberAgentInfo["id"];
            if( $batchAction == "status" ){
                $status = $this->_post("status");
                if( $status != 1 && $status != 2 ){
                    $this->ajaxError('上下架状态参数不合法！');
                }
                $trademarks = array();
                $trademarks['status'] = $status;
                $trademarks['updated_at'] = date("Y-m-d H:i:s");
                $res = M("trademarks")->where($where)->save($trademarks);
                if( $res <= 0 ){
                    $this->ajaxError('修改上下架失败！');
                }
                $this->ajaxSuccess('修改上下架成功！');
            }
            if( $batchAction == "saleStatus" ){
                $saleStatus = $this->_post("saleStatus");
                if( $saleStatus != 0 && $saleStatus != 1 ){
                    $this->ajaxError('卖出状态参数不合法！');
                }
                $trademarks = array();
                $trademarks['sale_status'] = $saleStatus;
                $trademarks['updated_at'] = date("Y-m-d H:i:s");
                $res = M("trademarks")->where($where)->save($trademarks);
                if( $res <= 0 ){
                    $this->ajaxError('修改卖出状态失败！');
                }
                $this->ajaxSuccess('修改卖出状态成功！');
            }
        }else{
            $this->display();
        }
    }

    /**
     * 批量删除
     */
    public function trademarksbatchdel(){
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }
        $ac = $this->_get('ac', 'trim', '');
        if( $ac == "setting" ){
            $trademarkSn = $this->_post("trademarkSn","trim");
            if( empty($trademarkSn) ){
                $this->ajaxError('请输入商标编号！');
            }
            $trademarkSn = explode("\n",$trademarkSn);
            $trademarkIds = array();
            for ($i = 0; $i < count($trademarkSn); $i++){
                $sn = trim($trademarkSn[$i]);
                if( !empty($sn) ){
                    //查询是否属于当前代理商；
                    $where = array();
                    $where['trademark_sn'] = $sn;
                    $where['agent_id'] = $memberAgentInfo["id"];
                    $where['is_deleted'] = 0;
                    $list = M("trademarks")->where($where)->select();
                    if( empty($list) ){
                        //$this->ajaxError("当前代理商下未检测到该商标：{$sn}！");
                        continue;
                    }
                    foreach ( $list as $k => $v ){
                        array_push($trademarkIds, $v['id']);
                    }
                }
            }
            if( count($trademarkIds) == 0 ){
                $this->ajaxError('未匹配出需要操作的商标！');
            }
            $where = array();
            $where['id'] = ["in",$trademarkIds];
            $where['agent_id'] = $memberAgentInfo["id"];
            $trademarks = array();
            $trademarks['is_deleted'] = 1;
            $trademarks['deleted_at'] = date("Y-m-d H:i:s");
            $res = M("trademarks")->where($where)->save($trademarks);
            if( $res <= 0 ){
                $this->ajaxError('删除失败！');
            }
            $this->ajaxSuccess('删除成功！');
        }else{
            $this->display();
        }
    }

    /**
     * 批量进行商标操作
     */
    public function trademarksbatchaction(){
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }
        $ac = $this->_get('ac', 'trim', '');
        if( $ac == "setting" ){
            $batchAction = $this->_post("action");
            if( $batchAction != "status" && $batchAction != "saleStatus" && $batchAction != "updatePrice" ){
                $this->ajaxError('操作类型不正确！');
            }
            $ids = $this->_post("ids");
            $ids = explode(",",$ids);
            $trademarkIds = array();
            for ($i = 0; $i < count($ids); $i++){
                $id = intval($ids[$i]);
                if( $id > 0 ){
                    array_push($trademarkIds, $id);
                }
            }
            if( count($trademarkIds) == 0 ){
                $this->ajaxError('请选择要操作的商标！');
            }
            $where = array();
            $where['id'] = ["in",$trademarkIds];
            $where['agent_id'] = $memberAgentInfo["id"];
            if( $batchAction == "status" ){
                $status = $this->_post("status");
                if( $status != 1 && $status != 2 ){
                    $this->ajaxError('上下架状态参数不合法！');
                }
                $trademarks = array();
                $trademarks['status'] = $status;
                $trademarks['updated_at'] = date("Y-m-d H:i:s");
                $res = M("trademarks")->where($where)->save($trademarks);
                if( $res <= 0 ){
                    $this->ajaxError('修改上下架失败！');
                }
                $this->ajaxSuccess('修改上下架成功！');
            }
            if( $batchAction == "saleStatus" ){
                $saleStatus = $this->_post("saleStatus");
                if( $saleStatus != 0 && $saleStatus != 1 ){
                    $this->ajaxError('卖出状态参数不合法！');
                }
                $trademarks = array();
                $trademarks['sale_status'] = $saleStatus;
                $trademarks['updated_at'] = date("Y-m-d H:i:s");
                $res = M("trademarks")->where($where)->save($trademarks);
                if( $res <= 0 ){
                    $this->ajaxError('修改卖出状态失败！');
                }
                $this->ajaxSuccess('修改卖出状态成功！');
            }
            if( $batchAction == "updatePrice" ){
                $this->ajaxError('功能已弃用！');
                $updatePriceType = $this->_post("updatePriceType");
                if( $updatePriceType != "all" && $updatePriceType != "add" && $updatePriceType != "cut" ){
                    $this->ajaxError('价格类型参数不合法！');
                }
                $updatePriceValue = $this->_post("updatePriceValue", "intval", 0);
                if( $updatePriceValue <= 0 ){
                    $this->ajaxError('金额参数不合法！');
                }
                if( $updatePriceValue > 9999999 ){
                    $this->ajaxError('金额最高不得超过9999999元！');
                }

                if( $updatePriceType == "all" ){
                    $trademarks = array();
                    $trademarks['trademark_price'] = $updatePriceValue;
                    $trademarks['updated_at'] = date("Y-m-d H:i:s");
                    $res = M("trademarks")->where($where)->save($trademarks);
                    if( $res <= 0 ){
                        $this->ajaxError('价格更新失败！');
                    }
                    $this->ajaxSuccess('价格更新成功！');
                }else{
                    $list = M("trademarks")->where($where)->field("id,trademark_price")->select();
                    foreach ( $list as $k => $v ){
                        $save = array();
                        if( $updatePriceType == "add" ) {
                            $save['trademark_price'] = $v['trademark_price'] + $updatePriceValue;
                        }else{
                            $save['trademark_price'] = $v['trademark_price'] - $updatePriceValue;
                        }
                        if( $save['trademark_price'] < 0 ){
                            $save['trademark_price'] = 0;
                        }
                        $save['updated_at'] = date("Y-m-d H:i:s");
                        $res = M("trademarks")->where(["id" => $v["id"]])->save($save);
                    }
                    $this->ajaxSuccess('价格更新成功！');
                }
            }
        }else{
            $ids = $this->_get('ids', 'trim');
            $this->assign('ids', $ids);
            $this->display();
        }
    }

    /**
     * 商标全部上架
     */
    public function setAllTrademarkStatusOn(){
        if ( !$this->checkLogin(true) ) {
            return $this->ajaxError('登录状态失效，请重新登录！');
        }
        if( !in_array($this->member['role_id'],array(3)) ){
            $this->error_notice("仅对代理角色开放！");
        }
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }

        $where = array();
        $where['status'] = ['in',[0,2]];
        $where['agent_id'] = $memberAgentInfo["id"];
        $count = M("trademarks")->where($where)->count();
        if( $count == 0 ){
            return $this->ajaxError('您的商标已全部处于上架状态，暂无可上架的商标！');
        }
        $trademarks = array();
        $trademarks['status'] = 1;
        $trademarks['updated_at'] = date("Y-m-d H:i:s");
        $res = M("trademarks")->where($where)->save($trademarks);
        if( $res <= 0 ){
            $this->ajaxError('全部上架失败！');
        }
        $this->ajaxSuccess('全部上架成功！');
    }

    /**
     * 全部删除
     */
    public function delAllTrademarks(){
        if ( !$this->checkLogin(true) ) {
            return $this->ajaxError('登录状态失效，请重新登录！');
        }
        if( !in_array($this->member['role_id'],array(3)) ){
            $this->error_notice("仅对代理角色开放！");
        }
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->error_notice('未检测到代理信息！');
        }
        $where = array();
        $where['is_deleted'] = 0;
        $where['agent_id'] = $memberAgentInfo["id"];
        $count = M("trademarks")->where($where)->count();
        if( $count == 0 ){
            return $this->ajaxError('暂无可删除的商标！');
        }
        $trademarks = array();
        $trademarks['is_deleted'] = 1;
        $trademarks['deleted_at'] = date("Y-m-d H:i:s");
        $res = M("trademarks")->where($where)->save($trademarks);
        if( $res <= 0 ){
            $this->ajaxError('删除失败！');
        }
        $this->ajaxSuccess('删除成功！');
    }

    /**
     * 商标导入
     */
    public function trademarksupload(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member/login.html');
            exit();
        }
        if( !in_array($this->member['role_id'],array(3)) ){
            $this->error_notice("仅对代理角色开放，暂无权限！");
        }
        $this->assign('randnumber', time().rand(100000,999999));
        $this->display();
    }

    /**
     * 商标导入
     */
    public function trademarksuploadFile(){
        if( !in_array($this->member['role_id'],array(3)) ){
            $this->error_notice("仅对代理角色开放，暂无权限！");
        }
        $randnumber = intval($this->_get("randnumber"));
        if( empty($randnumber) || $randnumber == 0 ){
            return $this->ajaxError('上传失败，未检测到上传安全码！');
        }
        if( !$_FILES ){
            return $this->ajaxError('上传失败，未检测到上传内容！');
        }
        //查询代理信息
        $memberAgentInfo = M("admin_agent_info")->where(array('admin_id' => $this->member['id']))->find();
        if( empty($memberAgentInfo) ){
            return $this->ajaxError('未检测到代理信息，不支持上传！');
        }
        $filewhere = array();
        $filewhere['admin_id'] = $this->member['id'];
        $filewhere['handle_status'] = ['in',[0,1]];
        $waitfile = M("trademarks_files")->where($filewhere)->find();
        if( $waitfile ){
            $this->ajaxError("您有待处理的文件，请等待处理结束！");
        }
        import('@.ORG.Util.StringUtil');
        import('@.ORG.Net.UploadFile');
        //临时路径
        $rootDir = UPLOAD_PATH . '/trademarksUploadFile/';
        $rootPath = $_SESSION['member']['id']."_".$_SESSION['member']['user_name'] . '/';
        $path = $rootDir . $rootPath;
        if (!is_dir($path)) {
            @mkdir($path, 0777);
        }
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize = 1024 * 1024 * 5;// 设置附件上传大小
        $upload->allowExts = explode(',', 'csv');
        $upload->savePath = $path; // 设置附件上传目录
        $upload->saveRule = date("YmdHis");
        if (!$upload->upload()) {//上传失败
            $this->errorMsg = $upload->getErrorMsg();
            $this->ajaxError($this->errorMsg);
        } else {//上传成功
            $info = $upload->getUploadFileInfo();
            $filepath = $path.$info[0]['savename'];
            $data['path'] = $rootPath . $info[0]['savename'];
            //读取数据
            $stringUtil = new StringUtil();
            $trademarkList = array();
            $fileData = $this->readCvs($filepath);
            foreach ($fileData as $key => $value) {
                if ($i > 0) {
                    if (is_array($value) && count($value) == 2) {
                        //数组元素整体去掉前后空格，保留中间空格
                        $value = array_map(function ($val){ return trim($val);},$value);
                        //提取变量
                        $trademark_sn = $value[0];
                        $trademark_sn = iconv("gbk","utf-8",$trademark_sn);
                        $trademark_price = intval($value[1]);
                        $trademark_sn = $stringUtil::delKongGe($trademark_sn);
                        if( empty($trademark_sn) ){
                            continue;
                        }
                        if( $trademark_price <= 0 ){
                            return $this->ajaxError("【".$trademark_sn."】价格不合规！");
                        }
                        $length = mb_strlen($trademark_sn);
                        //字符串转数组
                        $char = array();
                        for( $i = 0; $i < $length; $i++ ){
                            $char[$i] = msubstr($trademark_sn, $i, 1);
                            //商标必须由数组和字母组成
                            if( !$stringUtil::isEnglish($char[$i]) && !$stringUtil::isNumeric($char[$i]) ){
                                return $this->ajaxError("【".$trademark_sn."】不是合法的商标标号！");
                            }
                        }
                        //商标信息
                        $trademark = array();
                        $trademark['trademark_sn'] = $trademark_sn;
                        $trademark['trademark_price'] = $trademark_price;
                        if( !isset($trademarkList[$trademark_sn]) ){
                            $trademarkList[$trademark_sn] = $trademark;
                        }
                    }
                }
                $i++;
            }
            if( empty($trademarkList) ){
                return $this->ajaxError("数据文件中未检测到合法的数据项！");
            }
            $file = array();
            $file['admin_id'] = $this->member['id'];
            $file['upload_file_path'] = $data['path'];
            $file['total_count'] = 0;
            $file['processed_count'] = 0;
            $file['suc_count'] = 0;
            $file['fail_count'] = 0;
            $file['fail_content'] = '[]';
            $file['handle_status'] = 0;
            $file['created_at'] = date("Y-m-d H:i:s");
            $res = M("trademarks_files")->add($file);
            if( $res <= 0 ){
                $this->ajaxError("上传文件入库失败");
            }
            $this->ajaxSuccess("上传成功，请等待处理！");
        }
    }

    /**
     * 获取商标上传结果
     */
    public function getTrademarksuploadResult(){
        $filewhere = array();
        $filewhere['admin_id'] = $this->member['id'];
        $filewhere['handle_status'] = ['in',[0,1,2]];
        $waitfile = M("trademarks_files")->where($filewhere)->order('id desc')->find();
        $result = array();
        $result['handleStatus'] = -1;
        if( $waitfile ){
            $result['handleStatus'] = $waitfile['handle_status'];
            $result['totalCount'] = $waitfile['total_count'];
            $result['processedCount'] = $waitfile['processed_count'];
            $result['sucCount'] = $waitfile['suc_count'];
            $result['failCount'] = $waitfile['fail_count'];
        }
        $this->ajaxSuccess("获取成功",$result);
    }

    /**
     * 获取商标上传结果
     */
    public function exportFailTrademarkResult(){
        $filename = '失败商标列表';
        $titles = array(
            array("name"=>"序号","cellWidth" => 10),
            array("name"=>"商标号","cellWidth" => 15),
            array("name"=>"价格(元)","cellWidth" => 15),
            array("name"=>"失败原因","cellWidth" => 20),
        );
        $filewhere = array();
        $filewhere['admin_id'] = $this->member['id'];
        $filewhere['handle_status'] = ['in',[0,1,2]];
        $waitfile = M("trademarks_files")->where($filewhere)->order('id desc')->find();
        if( $waitfile ){
            $failTrademarks = json_decode($waitfile['fail_content'],true);
            $i = 0;
            foreach ( $failTrademarks as $k => $v ) {
                $temp = [
                    ( $i + 1 ),
                    $v['trademark_sn'],
                    $v['trademark_price'],
                    $v['message']
                ];
                $datalist[] = $temp;
                $i++;
            }
            $this->exportExcel($titles, $datalist, $filename, "失败商标列表");
            exit();
        }
        $this->ajaxSuccess("获取成功");
    }

    /**
     * 读取cvs文件
     * @param $filePath
     * @return Generator
     */
    private function readCvs($filePath){
        if (file_exists($filePath)) {
            # code...
            $handle = fopen($filePath, 'rb');
            while (feof($handle)===false) {
                # code...
                yield fgetcsv($handle);
            }
            fclose($handle);
        }
    }

}